import wepy from 'wepy'
export default class extends wepy.mixin {
    data = {
        // 搜索框内容
        value: '',
        // 搜索建议列表
        suggestList: [],
        // 搜索历史列表
        kwList: []
    }
    methods = {
        // 输入内容变化时，获取输入的关键字
        onChange(e) {
            this.value = e.detail.trim()
            if (e.detail.trim().length <= 0) {
                this.suggestList = []
                return
            }
            this.getSuggestList(e.detail)
        },
        // 触发搜索
        onSearch(e) {
            var kw = e.detail.trim()
            // 搜索关键字为空，停止跳转
            if (kw.length <= 0) {
                return
            }
            // 判断用户输入的值是否已经存在 kwList 中, 存在就不unshift
            if (this.kwList.indexOf(kw) === -1) {
                this.kwList.unshift(kw)
            }
            // 让 kwList 只保存10条数据
            this.kwList = this.kwList.slice(0, 10)
            wepy.setStorageSync('kw', this.kwList);
            wepy.navigateTo({
                url: '/pages/goods_list?query=' + kw
            })
        },
        // 触发取消
        onCancel() {
            this.suggestList = []
        },
        // 点击进入商品详情页面
        goGoodsDetail(goodsId) {
            wepy.navigateTo({ url: '/pages/goods_detail/main?goods_id=' + goodsId });

        },
        // 点击历史进入商品详情页面
        goGoodsList(item) {
            wepy.navigateTo({ url: '/pages/goods_list?query=' + item });

        },
        // 点击删除图标清空历史列表数据
        deletekwList() {
            this.kwList = []
            wepy.setStorageSync('kw', [])
        }
    }
    computed = {
        isShowHistory() {
            if (this.value.length <= 0) {
                return true
            }
            return false
        }
    }
    async getSuggestList(searchStr) {
        const { data: res } = await wepy.get('/goods/qsearch', { query: searchStr })
        if (res.meta.status !== 200) {
            return wepy.baseToast()
        }
        this.suggestList = res.message
        this.$apply()
    }
    onLoad() {
        // 页面加载期间获取关键字
        const kwList = wepy.getStorageSync('kw') || []
        this.kwList = kwList
    }
}